package com.weishi.project.training.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weishi.common.utils.DateUtils;
import com.weishi.common.utils.StringUtils;
import com.weishi.project.api.vo.*;
import com.weishi.project.sport.home.vo.ClassifiedTotalVO;
import com.weishi.project.sport.home.vo.GetLandGlidingSumVO;
import com.weishi.project.sport.home.vo.ThisWeekTrainingDataVO;
import com.weishi.project.sport.movement.vo.ReturnTrainingDayVO;
import com.weishi.project.training.domain.TrainingDay;
import com.weishi.project.training.domain.TrainingGroup;
import com.weishi.project.training.domain.TrainingGroupChannel;
import com.weishi.project.training.domain.TrainingWeek;
import com.weishi.project.training.mapper.TrainingDayMapper;
import com.weishi.project.training.mapper.TrainingGroupChannelMapper;
import com.weishi.project.training.mapper.TrainingGroupMapper;
import com.weishi.project.training.service.ITrainingDayService;
import com.weishi.project.training.vo.TrainingDayAddVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * trainingDayService业务层处理
 */
@Service
public class TrainingDayServiceImpl extends ServiceImpl<TrainingDayMapper, TrainingDay> implements ITrainingDayService {

    @Autowired
    private TrainingDayMapper trainingDayMapper;

    @Autowired
    private TrainingGroupMapper trainingGroupMapper;

    @Autowired
    private TrainingGroupChannelMapper trainingGroupChannelMapper;

    /**
     * 查询trainingDay列表
     */
    @Override
    public List<TrainingDay> selectTrainingDayList(TrainingDay trainingDay) {
        return trainingDayMapper.selectTrainingDayList(trainingDay);
    }

    @Override
    public List<TrainingWeek> getWeekName() {
        return trainingDayMapper.getWeekName();
    }

    @Override
    public TrainingDay getTrainingDayById(int id) {
        return trainingDayMapper.getTrainingDayById(id);
    }

    @Override
    public void updateTrainingWeekById(TrainingDay trainingDay) {
        //更新训练日项目实际完成公里数（测功仪）
        /*if(trainingDay.getCompletion()>0d && trainingDay.getIdealKilometers()!=null && trainingDay.getIdealKilometers()!=0){
            //查询实际组数
            TrainingGroup params = new TrainingGroup();
            params.setTrainingDayId(trainingDay.getId());
            List<TrainingGroup> trainingGroups = trainingGroupMapper.selectTrainingGroupList(params);
            if(trainingGroups.size()>0){
                trainingDay.setKilometers(trainingDay.getIdealKilometers()*trainingGroups.size());
            }
        }*/

        if(trainingDay.getRealClassHour()==0){
            getClassHour(trainingDay);
        }
        trainingDayMapper.updateById(trainingDay);
    }

    @Override
    public List<TrainingDay> selectTrainingDayListByNaturalYearId(int naturalYearId) {
        return trainingDayMapper.selectTrainingDayListByNaturalYearId(naturalYearId);
    }

    @Override
    public List<Map<String, Object>> selectWeekTrainingData(WeekTrainingCompletionVo weekTrainingCompletionVo) {
        return trainingDayMapper.selectWeekTrainingData(weekTrainingCompletionVo);
    }

    @Override
    public List<Map<String, Object>> weekTrainingAchievementCompletion(WeekTrainingCompletionVo weekTrainingCompletionVo) {
        return trainingDayMapper.selectWeekTrainingAchievementCompletion(weekTrainingCompletionVo);
    }

    @Override
    public List<TrainingDay> selectTrainingDayListByDay(String day) {
        return trainingDayMapper.selectTrainingDayListByDay(day);
    }

    @Override
    public List<Map<String, Object>> waterSpecialPromotion(WaterSpecialPromotionVo waterSpecialPromotionVo) {
        return trainingDayMapper.waterSpecialPromotion(waterSpecialPromotionVo);
    }

    @Override
    public List<TrainingDay> selectTrainingDayBeforedawn(String day) {
        return trainingDayMapper.selectTrainingDayBeforedawn(day);
    }

    @Override
    public List<TrainingDay> selectTrainingDayMorning(String day) {
        return trainingDayMapper.selectTrainingDayMorning(day);
    }

    @Override
    public List<TrainingDay> selectTrainingDayAfternoon(String day) {
        return trainingDayMapper.selectTrainingDayAfternoon(day);
    }

    @Override
    public List<TrainingDay> selectTrainingDayNight(String day) {
        return trainingDayMapper.selectTrainingDayNight(day);
    }

    @Override
    public int getIdByFourSeasonsAndFirstLevelAndDay(Map<String, Object> map) {
        return trainingDayMapper.getIdByFourSeasonsAndFirstLevelAndDay(map);
    }

    @Override
    public int getIdByWeekIdAndDay(Map<String, Object> map) {
        return trainingDayMapper.getIdByWeekIdAndDay(map);
    }

    @Override
    public List<TrainingDayDetailsVo> getTrainingDayListDetails(TrainingDayDetailsVo trainingDayDetailsVo) {
        return trainingDayMapper.getTrainingDayListDetails(trainingDayDetailsVo);
    }

    @Override
    public List<TrainingDayWeekOrDayVo> getTrainingDayWeekOrDayVo(Map<String, Object> params) {
        return trainingDayMapper.getTrainingDayWeekOrDayVo(params);
    }

    @Override
    public List<TrainingDayKilometerWeekOrDayVo> getTrainingDayKilometerWeekOrDayVo(Map<String, Object> params) {
        return trainingDayMapper.getTrainingDayKilometerWeekOrDayVo(params);
    }

    @Override
    public List<TrainingDaySecondLevelHourWeekOrDayVo> getTrainingDaySecondLevelHourWeekOrDayVo(Map<String, Object> params) {
        return trainingDayMapper.getTrainingDaySecondLevelHourWeekOrDayVo(params);
    }

    @Override
    public List<TrainingDayKilometerSecondLevelWeekOrDayVo> getTrainingDayKilometerSecondLevelWeekOrDayVo(Map<String, Object> params) {
        return trainingDayMapper.getTrainingDayKilometerSecondLevelWeekOrDayVo(params);
    }

    @Override
    public void aggregateData(Integer trainingDayId) {
        TrainingDay trainingDay = trainingDayMapper.selectById(trainingDayId);
        trainingDay.setId(trainingDayId);
        int real_kilometers = 0;
        if(trainingDay!=null && trainingDay.getTrainingMode()==0){
            TrainingGroup params = new TrainingGroup();
            params.setTrainingDayId(trainingDayId);
            List<TrainingGroup> list = trainingGroupMapper.selectTrainingGroupList1(params);
            for(TrainingGroup trainingGroup : list){
                real_kilometers += trainingGroup.getKilometer();
            }
        }
        trainingDay.setKilometers(real_kilometers);
        trainingDayMapper.updateKilometersById(trainingDay);
    }

    @Override
    public boolean updateById(TrainingDay entity) {
        getClassHour(entity);
        return super.updateById(entity);
    }

    @Transactional
    @Override
    public boolean save(TrainingDay entity,boolean addTrainingGroup) {
        //getClassHour(entity);
        boolean ret = super.save(entity);
        if(addTrainingGroup){
            int numberGroups = entity.getNumberGroups()==null ? 1:entity.getNumberGroups();
            for(int i =0;i<numberGroups;i++){
                TrainingGroup trainingGroup = new TrainingGroup();
                trainingGroup.setCtime(new Date());
                trainingGroup.setTrainingDayId(entity.getId());
                trainingGroup.setWeekId(entity.getWeekId());
                trainingGroup.setType(entity.getFirstLevel());
                trainingGroup.setGroupName("第"+(i+1)+"组");
                trainingGroup.setKilometer(0);
                trainingGroup.setDay(DateUtils.dateTime("yyyy-MM-dd",entity.getDay()));
                trainingGroupMapper.insert(trainingGroup);
            }
        }
        return ret;
    }

    @Override
    public boolean saveOrUpdate(TrainingDay entity) {
        getClassHour(entity);
        return super.saveOrUpdate(entity);
    }

    private void getClassHour(TrainingDay entity) {
        String startTime = entity.getStartTime();
        String endTime = entity.getEndTime();
        if (StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime)) {
            int sd = Integer.parseInt(startTime.split(":")[0])*60 + Integer.parseInt(startTime.split(":")[1]);
            int ed = Integer.parseInt(endTime.split(":")[0])*60 + Integer.parseInt(endTime.split(":")[1]);
            int time = ed - sd;
            if (time > 0) {
                entity.setRealClassHour(time);
            } else {
                entity.setRealClassHour(0);
            }
        }
    }

    @Override
    public List<TrainingDay> getTrainingDayByWeekId(Integer weekId) {
        TrainingDay params = new TrainingDay();
        params.setWeekId(weekId);
        return trainingDayMapper.selectTrainingDayList(params);
    }

    @Override
    public Map<String, Object> getTrainingDayInfoById1(Integer id) {
        TrainingDay trainingDay = this.trainingDayMapper.selectById(id);
        if(trainingDay==null){
            return null;
        }
        Map<String, Object> ret = BeanUtil.beanToMap(trainingDay);
        //小组
        TrainingGroup params = new TrainingGroup();
        params.setTrainingDayId(trainingDay.getId());
        List<TrainingGroup> list = trainingGroupMapper.selectTrainingGroupList1(params);
        List<Map<String, Object>> trainingGroupList = new ArrayList<>();
        ret.put("trainingGroup",trainingGroupList);
        for(TrainingGroup trainingGroup : list){
            Map<String, Object> trainingGroupMap = BeanUtil.beanToMap(trainingGroup);
            trainingGroupList.add(trainingGroupMap);
            //航道
            TrainingGroupChannel trainingGroupChannelParams = new TrainingGroupChannel();
            trainingGroupChannelParams.setGroupId(trainingGroup.getId());
            List<TrainingGroupChannel> trainingGroupChannelList = trainingGroupChannelMapper.selectTrainingGroupChannelList(trainingGroupChannelParams);

            Map<String,List<TrainingGroupChannel>> batch = new HashMap<>();
            for(TrainingGroupChannel trainingGroupChannel : trainingGroupChannelList){
                String bacthStr ="";
                if(StringUtils.isNotNull(trainingGroupChannel.getBatch())){
                    bacthStr= "第" +(trainingGroupChannel.getBatch()+1) +"批次";
                }
                List<TrainingGroupChannel> batchList = batch.get(bacthStr);
                if(batchList==null){
                    batchList = new ArrayList<>();
                }
                batchList.add(trainingGroupChannel);
                batch.put(bacthStr,batchList);
            }

            List<List<TrainingGroupChannel>> lists = new ArrayList<>();
            //排序
            List<String> temp = new ArrayList<>(batch.keySet());
            Collections.sort(temp);
            for(String key : temp){
                lists.add(batch.get(key));
            }
            //航道分组批次
            trainingGroupMap.put("trainingGroupChannel",lists);
        }
        return ret;
    }

    /**
     * 训练数据查询运动员训练距离
     */
    @Override
    public Integer getDistance(Integer sportsmanId) {
        return trainingDayMapper.getDistance(sportsmanId);
    }



    /**
     * 训练数据查询运动员训练 水上训练次数
     */
    @Override
    public Integer getWaterFrequency(Integer sportsmanId) {
        return trainingDayMapper.getWaterFrequency(sportsmanId);
    }



    /**
     * 训练数据查询运动员训练 水上训练次数
     */
    @Override
    public Integer getLandNumber(Integer sportsmanId) {
        return trainingDayMapper.getLandNumber(sportsmanId);
    }



    /**
     * 查询运动员身体准备训练--根据传参-年-查询所有月的统计 ( 按照 分钟 统计 )
     */
    @Override
    public Double getPrepareMonth(Integer userId, String years, List<String> dayList) {
        return trainingDayMapper.getPrepareMonth(userId , years , dayList);
    }



    /**
     * 查询返回值  一年中 二级科目的时间占比
     */
    @Override
    public Double getReturnLevelTwoVO(Integer userId, String years , String ballGames , List<String> dayList) {
        return trainingDayMapper.getReturnLevelTwoVO(userId , years , ballGames , dayList);
    }


    /**
     * 根据年 来统计 运动员身体准备训练时间 二级科目 所占的百分比
     */
    @Override
    public Integer getStringVO(Integer userId, String years , String ballGames , List<String> dayList) {
        return trainingDayMapper.getStringVO(userId , years , ballGames , dayList);
    }


    /**
     * 水上专项训练 训练距离 滑行时长 统计
     */
    @Override
    public Double returnMonthVO(String year, Integer userId, Integer trainingMode, List<String> dayList) {
        return trainingDayMapper.returnMonthVO(year , userId , trainingMode , dayList);
    }


    /**
     * 水上专项训练 训练时间 滑行距离 统计
     */
    @Override
    public Double returnMonthTimeVO(String year, Integer userId, Integer trainingMode, List<String> dayList) {
        return trainingDayMapper.returnMonthTimeVO(year , userId , trainingMode ,dayList);
    }


    /**
     * 运动员 -- 本周训练数据
     */
    @Override
    public List<ThisWeekTrainingDataVO> getThisWeekTrainingDataVO(String day) {
        return trainingDayMapper.getThisWeekTrainingDataVO(day);
    }


    /**
     * 运动员 -- 根据训练分类查询总计
     */
    @Override
    public List<ClassifiedTotalVO> getClassifiedTotal(String day , Integer userId) {
        return trainingDayMapper.getClassifiedTotal(day , userId);
    }


    /**
     * 运动员 -- 首页 -- 陆上专项滑行统计 Sum
     */
    @Override
    public List<GetLandGlidingSumVO> getLandGlidingSum(String year, Integer userId, Integer trainingMode , List<String> dayList) {
        return trainingDayMapper.getLandGlidingSum(year , userId , trainingMode ,dayList);
    }


    /**
     * 运动员端--查询运动计划详情
     */
    @Override
    public List<ReturnTrainingDayVO> getSportsPlanDetails(Integer userId , Integer id) {
        return trainingDayMapper.getSportsPlanDetails(userId , id);
    }


    /**
     * 运动员端--查询运动--乳酸
     */
    @Override
    public List<String> getLacticAcid(Integer userId , String firstLevel , Integer trainingMode , Integer groupId , Integer trainingDayId) {
        return trainingDayMapper.getLacticAcid(userId , firstLevel , trainingMode , groupId , trainingDayId);
    }


    /**
     * 运动员端--查询运动--专项成绩信息
     */
    @Override
    public List<ReturnTrainingDayVO> getWaterInformation(Integer userId, Integer id , Integer trainingMode , String firstLevel , Integer groupId) {
        return trainingDayMapper.getWaterInformation(userId , id , trainingMode , firstLevel , groupId);
    }


    /**
     * 查询运动员专项最好成绩
     */
    @Override
    public String getPersonalBest(Integer userId, Integer trainingMode , String firstLevel) {
        return trainingDayMapper.getPersonalBest(userId , trainingMode , firstLevel);
    }


    @Override
    @Transactional
    public void addTrainingDayAndTrainingGroup(TrainingDayAddVo trainingDayAddVo) {
        TrainingDay trainingDay = trainingDayAddVo.getTrainingDay();
        trainingDay.setCtime(new Date());
        super.save(trainingDay);

        List<TrainingGroup> trainingGroups = trainingDayAddVo.getTrainingGroups();
        if(trainingGroups!=null && trainingGroups.size()!=0){
            for(TrainingGroup trainingGroup : trainingGroups){
                trainingGroup.setCtime(new Date());
                trainingGroup.setTrainingDayId(trainingDay.getId());
                trainingGroup.setWeekId(trainingDay.getWeekId());
                trainingGroupMapper.insert(trainingGroup);
            }
        }
    }


    /**
     * 运动员端--查询运动计划详情第二次查询
     */
    @Override
    public List<ReturnTrainingDayVO> getSportsPlanDetailsTwo(Integer id , Integer userId) {
        return trainingDayMapper.getSportsPlanDetailsTwo(id , userId);
    }







}